package yl.hs.bmipfull.utils;

import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 作用: 文件工具类  <br/>
 * 创建时间: 2021-05-14 10:44 <br/>
 *
 * @author 张凯
 */
public class
FileUtil {
    public static final String FILE_KEY = "YLHS@FILEKEY_xxil9tMH063v";


    /**
     * 加密上传文件
     *
     * @param realPath 文件路径
     * @param fileName 文件名称
     * @param file     文件
     * @return 执行结果
     */
    public static boolean upload(String realPath, String fileName, MultipartFile file) {

        File dest = new File(realPath + File.separator + fileName);
        var tempFile = new File(realPath + File.separator + "temp" + File.separator + fileName);

        //判断目录是否存在
        if (!tempFile.getParentFile().exists()) {
            boolean b = tempFile.getParentFile().mkdirs();
            if (!b) {
                return b;
            }
        }
        if (tempFile.isFile() && tempFile.exists()) {
            tempFile.delete();
        }

        //保存文件
        try {
            dest = AESUtil.encryptFile(file, dest, FILE_KEY);
            file.transferTo(dest);
            return true;
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return false;
        }

    }

    public static File loadFile(String path) throws IOException {
        File file = new File(path);
        FileInputStream fileInputStream = new FileInputStream(file);

        MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        return AESUtil.decryptFile(multipartFile, file, FILE_KEY);

    }

    public static String getFileName(MultipartFile file) {
        var contentType = file.getContentType().toLowerCase();
        var extend = "";
        switch (contentType) {
            case "image/png":
                extend = ".png";
                break;
            case "image/gif":
                extend = ".gif";
                break;
            case "image/jpg":
                extend = ".jpg";
                break;
            case "image/jpeg":
                extend = ".jpg";
                break;
            case "image/bmp":
                extend = ".bmp";
                break;

        }
        var stf = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
        return stf.format(new Date()) + extend;

    }
}
